package com.base.component.ai.platform.prompt;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.base.component.ai.agent.core.prompt.PromptLogHandler;
import com.base.component.ai.platform.ImageCompletionsHandler;
import com.base.component.ai.platform.core.bo.common.ImageCompletionsBO;
import com.base.core.head.dto.ai.MessageImageDTO;
import com.gitee.magic.core.exception.ApplicationException;

import lombok.extern.slf4j.Slf4j;

/**
 * 组件服务
 * 
 * @author zywei
 *
 */
@Slf4j
@Service
public class PromptTemplateImageService<M extends MessageImageDTO> {

	@Autowired(required = false)
	private List<PromptLogHandler<ImageCompletionsBO<M>,M>> promptLogHandlers;
	@Autowired
	private List<ImageCompletionsHandler<M>> imageCompletionsHandler;
	
	/**
	 * 获取所有支持的模型
	 * @return
	 */
	public List<String> getSupportModel(){
		List<String> models=new ArrayList<>();
		for(ImageCompletionsHandler<M> handler:imageCompletionsHandler) {
			models.addAll(handler.getSupportModel());
		}
		return models;
	}
	
	public void execute(ImageCompletionsBO<M> param,Class<M> cls,Consumer<String> process) {
		for(ImageCompletionsHandler<M> handler:imageCompletionsHandler) {
			if(handler.support(param.getModel())) {
				StringBuilder sb=new StringBuilder();
				handler.execute(param,(c)->{
					log.info("agent :{} model:{} requestId:{} response: {}",param.getCode(),param.getModel(),param.getRequestId(),c);
					sb.append(c);
					process.accept(c);
				});
				if(!CollectionUtils.isEmpty(promptLogHandlers)) {
					for(PromptLogHandler<ImageCompletionsBO<M>,M> logHandler:promptLogHandlers) {
						if(logHandler.support(cls)) {
							logHandler.saveLog(param, sb.toString());
						}
					}
				}
				return;
			}
		}
		throw new ApplicationException("找不到执行模型："+param.getModel() +" code:"+param.getCode());
	}
	
}
